package com.kingyea.mobilepolice.systemsync;

import com.kingyea.mobilepolice.system.StateCode;
import com.kingyea.mobilepolice.system.exception.BusinessException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ConstPool;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.BooleanMemberValue;

/**
 * 测试
 *
 * @author Mr.Lin
 * @version v1.0.0
 * @description
 * @date Created in 2018/4/28 17:40
 */

public class SyncServiceSwitch {


    public static void changeAnnotataion(String canonicalName, String methodName, boolean value, String valKey) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        //获取要修改的类的所有信息
        CtClass ct = pool.get(canonicalName);
        //获取类中的方法
        CtMethod[] cms = ct.getDeclaredMethods();
        //获取方法
        CtMethod cm = null;
        for (CtMethod ctMethod : cms) {
            if (ctMethod.getName().equalsIgnoreCase(methodName)) {
                cm = ctMethod;
                break;
            }
        }
        if (null == cm) {
            throw new BusinessException(StateCode.SYSTEM_ERROR, "找不到 " + methodName + " 方法");
        }
//        System.out.println("方法名称====" + cm.getName()+"  >>>  "+cm.getLongName());
        //获取方法信息
        MethodInfo methodInfo = cm.getMethodInfo();

        //获取所有的注解属性
        AnnotationsAttribute attribute = (AnnotationsAttribute) methodInfo.getAttribute(AnnotationsAttribute.visibleTag);
//        System.out.println(attribute);
        //获取注解
        Annotation annotation = attribute.getAnnotation(Send2Queue2.class.getName());
//        System.out.println(annotation);
        //获取注解的值
        Object memberVal = annotation.getMemberValue(valKey);
        System.out.println("修改前注解===" + valKey + " : " + memberVal);
//        System.out.println(annotation.getMemberNames());


        System.out.println("*******************************************************************************");

        ConstPool cp = methodInfo.getConstPool();
        //获取注解信息

        //修改名称为unitName的注解
        annotation.addMemberValue(valKey, new BooleanMemberValue(value, cp));
        attribute.setAnnotation(annotation);
        methodInfo.addAttribute(attribute);

        //打印修改后方法
        Annotation annotation3 = attribute.getAnnotation(Send2Queue2.class.getName());

        System.out.println("修改后的注解名称===" + valKey + " : " + annotation3.getMemberValue(valKey));
    }


}
